//
//  DelinquentCustomersViewController
//  Balance
//
//  Created by Sophia Tsay on 6/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DelinquentCustomersViewController.h"
#import "TopDelinquentCustomersViewController.h"
#import "ColorUtility.h"
#import "CEIViewController.h"
#import "BalanceDetailViewController.h"

/*
#define delinquentCustomers [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys: @"Apple Inc", @"Customer",[NSNumber numberWithInt: 5000000], @"Total Delinquent",[NSNumber numberWithInt: 7000000], @"Total Open Receivables",[NSNumber numberWithInt: 49], @"DSO",@" ", @"DSO Trend",[NSNumber numberWithInt: 15], @"DSO Change",[NSNumber numberWithInt: 15], @"Percent 91+ Delinquent",[NSNumber numberWithInt: 34], @"WADD",[NSNumber numberWithInt: 49], @"Best Possible DSO",[NSNumber numberWithInt: 49], @"True DSO",[NSNumber numberWithInt: 49], @"Percent Current",[NSNumber numberWithInt: 49], @"Sales Weighted DSO",[NSNumber numberWithInt: 49], @"Weighted Average Terms",[NSNumber numberWithInt: 49], @"Average Days Delinquent",[NSNumber numberWithInt: 49], @"Weighted Average Days Late",[NSNumber numberWithInt: 49], @"Weighted Average Days Paid",[NSNumber numberWithInt: 54], @"Score",@" ", @"Score Trend",@"Hard Call", @"Assigned Strategy", @"Matt Cooke", @"Collectr",nil],nil]
*/

#define notifications [NSArray arrayWithObjects:@"Credit Hold", @"Order Hold", @"Approval for Dispute", @"Overdue Promise", @"Pre-delinquency", @"Strategy Work Items", @"Customer Reassignments",nil]

#define KPIHeaders [NSArray arrayWithObjects: @"Name", @"Value", @"Target", @"Variance", @"Change", nil]

#define KPIValues [NSArray arrayWithObjects:[NSArray arrayWithObjects:@"DSO", @"24", @"20", @"4", @"20", nil], [NSArray arrayWithObjects:@"True DSO", @"22.5", @"17", @"-5.5", @"24", nil], [NSArray arrayWithObjects:@"Best Possible DSO", @"29", @"16", @"13.0", @"54", nil], [NSArray arrayWithObjects:@"Sales Weighted DSO", @"31", @"25", @"6.0", @"18", nil], [NSArray arrayWithObjects:@"Average Days Delinquent", @"4.5", @"3.0", @"1.5", @"-10", nil], [NSArray arrayWithObjects:@"Weighted Average Days Late", @"3.2", @"5.0", @"-1.8", @"-9", nil], [NSArray arrayWithObjects:@"Weighted Average Days Paid", @"7.5", @"4.0", @"-2.5", @"16", nil], [NSArray arrayWithObjects:@"Percent Current", @"92", @"98", @"6", @"-33", nil], [NSArray arrayWithObjects:@"Percent Delinquent", @"8", @"2", @"6", @"66", nil], [NSArray arrayWithObjects:@"Weighted Average Terms", @"5.0", @"15", @"10.0", @"66", nil], [NSArray arrayWithObjects:@"Score", @"75", @"72", @"3", @"2", nil], [NSArray arrayWithObjects:@"CEI", @"75", @"72", @"3", @"2", nil],nil]

#define kNumberOfPages 2

@interface DelinquentCustomersViewController ()
@property (strong, nonatomic) IBOutlet UITableView *notificationTableView;
@property (strong, nonatomic) IBOutlet MDSpreadView *KPISpreadView;
@property (strong, nonatomic) IBOutlet UIButton *balanceView;
@property (strong, nonatomic) IBOutlet UILabel *notificationHeaderView;
@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) IBOutlet UIPageControl *pageControl;
@property (strong, nonatomic) IBOutlet UIView *bottomBackgroundView;
@property (strong, nonatomic) IBOutlet UIView *backgroundView1;
@property (strong, nonatomic) IBOutlet UIScrollView *notificationScrollView;
@property (strong, nonatomic) IBOutlet UIView *backgroundView2;
@property (strong, nonatomic) IBOutlet UIView *backgroundView3;
@end

@implementation DelinquentCustomersViewController
@synthesize notificationTableView = _notificationTableView;
@synthesize KPISpreadView = _KPISpreadView;
@synthesize balanceView = _balanceView;
@synthesize notificationHeaderView = _notificationHeaderView;
@synthesize scrollView = _scrollView;
@synthesize pageControl = _pageControl;
@synthesize bottomBackgroundView = _bottomBackgroundView;
@synthesize backgroundView1 = _backgroundView1;
@synthesize notificationScrollView = _notificationScrollView;
@synthesize backgroundView2 = _backgroundView2;
@synthesize backgroundView3 = _backgroundView3;
@synthesize spreadView = _spreadView; 
@synthesize collectorName = _collectorName;


- (void)setNotificationTableView:(UITableView *)notificationTableView
{
    _notificationTableView = notificationTableView;
    self.notificationTableView.backgroundView = nil;
    self.notificationTableView.backgroundColor = [UIColor whiteColor];
    self.notificationTableView.delegate = self;
    self.notificationTableView.dataSource = self;
    //self.notificationTableView.layer.cornerRadius = 8.0f;
    //UILabel *tableHeaderLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.notificationTableView.frame.origin.x, self.notificationTableView.frame.origin.y, self.notificationTableView.frame.size.width, 36)];
    //tableHeaderLabel.text = @"";
    //[self.notificationTableView.tableHeaderView addSubview:tableHeaderLabel];
}

/*
- (void) setSpreadView:(MDSpreadView *)spreadView
{
    _spreadView = spreadView;
    self.spreadView.layer.cornerRadius = 8.0f;
}

- (void) setBalanceView:(UIButton *)balanceView
{
    _balanceView = balanceView;
    self.balanceView.layer.cornerRadius = 8.0f;
}

- (void) setNotificationHeaderView:(UILabel *)notificationHeaderView
{
    _notificationHeaderView = notificationHeaderView;
    self.notificationHeaderView.layer.cornerRadius = 8.0f;
}
*/
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.spreadView reloadData];
    [self.KPISpreadView reloadData];
    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * kNumberOfPages, self.scrollView.frame.size.height);
    self.notificationScrollView.contentSize = CGSizeMake(self.notificationScrollView.frame.size.width * kNumberOfPages, self.notificationScrollView.frame.size.height);
    
    self.scrollView.delegate = self;
    self.scrollView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"background.tile.png"]];
    self.notificationScrollView.delegate = self;
    self.notificationScrollView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"background.tile.png"]];
    self.bottomBackgroundView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"background.tile.png"]];
    self.backgroundView1.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"background.tile.png"]];
    self.backgroundView2.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"background.tile.png"]];
    self.backgroundView3.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"background.tile.png"]];

    self.pageControl.numberOfPages = kNumberOfPages;
    self.notificationTableView.hidden = YES;
}

- (void)viewDidUnload
{
    [self setSpreadView:nil];
    [self setNotificationTableView:nil];
    [self setKPISpreadView:nil];
    [self setBalanceView:nil];
    [self setNotificationHeaderView:nil];
    [self setScrollView:nil];
    [self setPageControl:nil];
    [self setBottomBackgroundView:nil];
    [self setNotificationScrollView:nil];
    [self setBackgroundView1:nil];
    [self setBackgroundView2:nil];
    [self setBackgroundView3:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    //return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return YES;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"CEIPopoverSegue"])
    {
        CEIViewController *ceiVC = (CEIViewController *)segue.destinationViewController;
        ceiVC.buttonsView.hidden = YES;
    } else if ([segue.identifier isEqualToString:@"BalancePopoverSegue"]) {
        UINavigationController *navigationController = segue.destinationViewController;
        BalanceDetailViewController *balanceViewController = (BalanceDetailViewController *)navigationController.topViewController;
        balanceViewController.buttonsView.hidden = YES;
    }
}

#pragma mark - Table view data source
/*
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    NSString *sectionTitle;
    if (section == 1) {
        sectionTitle = @"Top Delinquent Customers";
    } else if (section == 0) {
        sectionTitle = @"Notifications";
    }
    return sectionTitle;
}
*/
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger numberOfRows = 0;
    if (section == 1) {
        //numberOfRows = [topDelinquentCustomers count];
        numberOfRows = 10;
    } else if (section == 0) {
        numberOfRows = [notifications count];
    }
    return numberOfRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *TopCellIdentifier = @"Top Delinquent Customers";
    static NSString *NotificationsCellIdentifier = @"Notifications";
    UITableViewCell *cell;
    
    if (indexPath.section == 1) {
        
        cell = [tableView dequeueReusableCellWithIdentifier:TopCellIdentifier];    
        cell.textLabel.text = [topDelinquentCustomers objectAtIndex:indexPath.row];
        //cell.detailTextLabel.text = @"Balance: $10,000.21 Overdue:$6,000";
        
    } else if (indexPath.section == 0) {
        
        cell = [tableView dequeueReusableCellWithIdentifier:NotificationsCellIdentifier];    
        cell.textLabel.text = [notifications objectAtIndex:indexPath.row];
        //cell.detailTextLabel.text = @"Balance: $10,000.21 Overdue:$6,000";
        
    }
    
    //cell.backgroundColor = [UIColor darkGrayColor];
    //cell.textLabel.textColor = [UIColor lightGrayColor];
    //cell.detailTextLabel.textColor = [UIColor whiteColor];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 2;
    [cell.textLabel sizeToFit];
    return cell;
}
/*
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 6, tableView.bounds.size.width -12, 12)];
    headerLabel.text = @"Notifications";
    headerLabel.textColor = [[UIColor alloc] initWithRed:85 green:85 blue:85 alpha:0.5];
    headerLabel.backgroundColor = [UIColor lightGrayColor];
    headerLabel.font = [UIFont systemFontOfSize:14];
    [headerView addSubview:headerLabel];
    headerView.backgroundColor = [UIColor lightGrayColor];
    return headerView;
}
*/
/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}

#pragma mark - Spread View Datasource

//no of columns per column section
- (NSInteger)spreadView:(MDSpreadView *)aSpreadView numberOfColumnsInSection:(NSInteger)section
{
    NSInteger numberOfColumns;
    if (aSpreadView == self.spreadView) {
        //Exclude Collector column for Collector tab.
        numberOfColumns = [delinquentCustomerHeaders count]-1;
    } else if (aSpreadView == self.KPISpreadView) {
        numberOfColumns = [KPIHeaders count];
    }
    return numberOfColumns;
}

//no or rows per row section
- (NSInteger)spreadView:(MDSpreadView *)aSpreadView numberOfRowsInSection:(NSInteger)section
{
    NSInteger numberOfRows;
    if (aSpreadView == self.spreadView) {
        //return [topDelinquentCustomers count];
        numberOfRows = [delinquentCustomerValues count];
        //return 6;
    } else if (aSpreadView == self.KPISpreadView) {
        numberOfRows = [KPIValues count];
    }
    return numberOfRows;
}

//no of column sections
- (NSInteger)numberOfColumnSectionsInSpreadView:(MDSpreadView *)aSpreadView
{
    //return 4;
    return 1;
}

// no of row sections
- (NSInteger)numberOfRowSectionsInSpreadView:(MDSpreadView *)aSpreadView
{
    //return 10;
    return 1;
}

#pragma mark Heights
// Comment these out to use normal values (see MDSpreadView.h)
/*
 - (CGFloat)spreadView:(MDSpreadView *)aSpreadView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {
 return 25+indexPath.row;
 }
 
 - (CGFloat)spreadView:(MDSpreadView *)aSpreadView heightForRowHeaderInSection:(NSInteger)rowSection
 {
 //    if (rowSection == 2) return 0; // uncomment to hide this header!
 
 return 22+rowSection*10;
 }
 */ 

- (CGFloat)spreadView:(MDSpreadView *)aSpreadView widthForColumnAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (aSpreadView == self.spreadView) {
        
        switch (indexPath.row) {
            case 0:  //customer
                return 135;
                break;
            case 1:  //Total Delinquent
                return 135;
                break;
            case 2:  //Open Receivables
                return 135;
                break;
            case 3:  //DSO
                return 60;
                break;
            case 4:
                return 130;
                break;
            case 5:
                return 170;
                break;
            case 6:
                return 70;
                break;
            case 7:
                return 140;
                break;
                
            default:
                return 170;
                break;
        }
    } else if (aSpreadView == self.KPISpreadView) {
        switch (indexPath.row) {
            case 0:  
                return 178;
                break;
            case 1:
                return 66;
                break;
            case 2:
                return 66;
                break;
            case 3:
                return 80;
            default:
                return 74;
                break;
        }
    }
     
    return 66;
}

/* 
 - (CGFloat)spreadView:(MDSpreadView *)aSpreadView widthForColumnHeaderInSection:(NSInteger)columnSection
 {
 //    if (columnSection == 2) return 0; // uncomment to hide this header!
 
 return 110+columnSection*50;
 }
 */
#pragma Cells
- (MDSpreadViewCell *)spreadView:(MDSpreadView *)aSpreadView cellForRowAtIndexPath:(NSIndexPath *)rowPath forColumnAtIndexPath:(NSIndexPath *)columnPath
{
    static NSString *cellIdentifier = @"Cell";
    
    MDSpreadViewCell *cell = [aSpreadView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[MDSpreadViewCell alloc] initWithStyle:MDSpreadViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    if (aSpreadView == self.spreadView) {
        NSArray *currentCustomer = [delinquentCustomerValues objectAtIndex:rowPath.row];

        cell.textLabel.text = [currentCustomer objectAtIndex:columnPath.row];        
        if (columnPath.row == 0 || columnPath.row == 18 || columnPath.row == 19) {
            cell.textLabel.textAlignment = UITextAlignmentLeft;
        } else {
            cell.textLabel.textAlignment = UITextAlignmentRight;
        }
    } else if (aSpreadView == self.KPISpreadView) {

        NSArray *currentKPI = [KPIValues objectAtIndex:rowPath.row];

        cell.textLabel.text = [currentKPI objectAtIndex:columnPath.row];
        if (columnPath.row == 0) {
            cell.textLabel.textAlignment = UITextAlignmentLeft;
        } else {
            cell.textLabel.textAlignment = UITextAlignmentRight;
        }
    }
    
    cell.textLabel.font = [UIFont systemFontOfSize:12];

    return cell;
}


//There are 3 types of header cells and the following 3 methods creating these cells for each type.
//CornerHeaderCell, RowHeaderCell,ColumnHeaderCell.
- (MDSpreadViewCell *)spreadView:(MDSpreadView *)aSpreadView cellForHeaderInRowSection:(NSInteger)rowSection forColumnSection:(NSInteger)columnSection
{
    static NSString *cellIdentifier = @"CornerHeaderCell";
    
    MDSpreadViewHeaderCell *cell = (MDSpreadViewHeaderCell *)[aSpreadView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[MDSpreadViewHeaderCell alloc] initWithStyle:MDSpreadViewHeaderCellStyleCorner reuseIdentifier:cellIdentifier];
    }
    
    cell.textLabel.text = [NSString stringWithFormat:@"Cor %d-%d", columnSection+1, rowSection+1];
    
    return cell;
}
//this is actually the header for each column
- (MDSpreadViewCell *)spreadView:(MDSpreadView *)aSpreadView cellForHeaderInRowSection:(NSInteger)section forColumnAtIndexPath:(NSIndexPath *)columnPath
{
    static NSString *cellIdentifier = @"RowHeaderCell";
    
    MDSpreadViewHeaderCell *cell = (MDSpreadViewHeaderCell *)[aSpreadView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[MDSpreadViewHeaderCell alloc] initWithStyle:MDSpreadViewHeaderCellStyleRow reuseIdentifier:cellIdentifier];
    }
    
    if (aSpreadView == self.spreadView) {
        cell.textLabel.text = [delinquentCustomerHeaders objectAtIndex:columnPath.row];    
        if (columnPath.row == 0 || columnPath.row == 18 || columnPath.row == 19) {
            cell.textLabel.textAlignment = UITextAlignmentLeft;
        } else {
            cell.textLabel.textAlignment = UITextAlignmentRight;
        }
    } else if (aSpreadView == self.KPISpreadView) {
        cell.textLabel.text = [KPIHeaders objectAtIndex:columnPath.row];    
        if (columnPath.row == 0) {
            cell.textLabel.textAlignment = UITextAlignmentLeft;
        } else {
            cell.textLabel.textAlignment = UITextAlignmentRight;
        }
    }

    cell.textLabel.frame = cell.frame;
    cell.textLabel.font = [UIFont systemFontOfSize:13];

    return cell;
}

//this is actually the header for each row
- (MDSpreadViewCell *)spreadView:(MDSpreadView *)aSpreadView cellForHeaderInColumnSection:(NSInteger)section forRowAtIndexPath:(NSIndexPath *)rowPath
{
    static NSString *cellIdentifier = @"ColumnHeaderCell";
    
    MDSpreadViewHeaderCell *cell = (MDSpreadViewHeaderCell *)[aSpreadView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[MDSpreadViewHeaderCell alloc] initWithStyle:MDSpreadViewHeaderCellStyleColumn reuseIdentifier:cellIdentifier];
    }
    
    cell.textLabel.text = [NSString stringWithFormat:@"%d (%d-%d)", section+1, rowPath.section+1, rowPath.row+1];
    
    return cell;
}

- (NSString *)spreadView:(MDSpreadView *)aSpreadView titleForHeaderInRowSection:(NSInteger)rowSection forColumnSection:(NSInteger)columnSection;
{
    return @"Delinquent Customers";
}
- (NSString *)spreadView:(MDSpreadView *)aSpreadView titleForHeaderInRowSection:(NSInteger)section forColumnAtIndexPath:(NSIndexPath *)columnPath;
{
    return @"Delinquent Customers";
}

- (NSString *)spreadView:(MDSpreadView *)aSpreadView titleForHeaderInColumnSection:(NSInteger)section forRowAtIndexPath:(NSIndexPath *)rowPath;
{
    return @"Delinquent Customers";
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    
    if (sender == self.scrollView) {
        // Update the page when more than 50% of the previous/next page is visible
        CGFloat pageWidth = self.scrollView.frame.size.width;
        int page = floor((self.scrollView.contentOffset.x - pageWidth / kNumberOfPages) / pageWidth) + 1;
        self.pageControl.currentPage = page;
    } 
}


- (IBAction)changePage:(UIPageControl *)sender{
    // update the scroll view to the appropriate page
    
    CGRect frame;
    frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
    frame.origin.y = 0;
    frame.size = self.scrollView.frame.size;
    [self.scrollView scrollRectToVisible:frame animated:YES];
}


/*
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    pageControlBeingUsed = NO;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    pageControlBeingUsed = NO;
}
*/

@end
